<?php
/*
 * @Author: 一品网络技术有限公司
 * @Date: 2022-09-18 20:56:03
 * @LastEditTime: 2022-09-26 20:53:02
 * @FilePath: \web\app\common\model\Admin.php
 * @Description:
 * 联系QQ:58055648
 * Copyright (c) 2022 by 东海县一品网络技术有限公司, All Rights Reserved.
 */

declare (strict_types = 1);

namespace app\admin\model;

use think\Model;
use think\facade\Db;
use think\facade\Config;

class Admin extends Model
{

    public static function onBeforeInsert($data)
    {
    }
    public static function onAfterInsert($data)
    {
    }
    public static function onBeforeUpdate($data)
    {
    }

    public static function onAfterRead($data){
        //分配权限
        $data=self::reauth($data);
        return $data;
    }

    public static function reauth($admin){
        if($admin->id==1){
            $rolesBtn = Mod::column('actions', 'name');
            foreach ($rolesBtn as $k => $v) {
                if($v){
                    $rolesBtn[$k] = json_decode($v);
                }
               
            }
            $admin->rolesBtn = $rolesBtn;
            $dataList = Rule::with('mod')->withoutField('name')->order('sort', 'asc')->select()->toArray();
            $dataList=self::rulebtn($dataList);
            $admin->routes = generateTree($dataList);
            

            return $admin;
        }
        $myrules=[];
        //继承的菜单
        $rolesRules = [];
        foreach ($admin->roles as $v) {
            if (is_array($v->rules)) {
                $rolesRules = array_merge($rolesRules, $v->rules);
            }
        }

        $rolesRules = array_values(array_unique($rolesRules));



        //额外菜单
        $cluderules = $admin->cluderules;
        $rolesRules = array_values(array_merge($rolesRules, $cluderules));

        //排除菜单
        $excluderules = $admin->excluderules;
        foreach ($rolesRules as $k => $v) {
            if (in_array($v, $excluderules)) {
                unset($rolesRules[$k]);
            }
        }

        $rolesRules = array_values($rolesRules);
        $myrules = $rolesRules;

        //继承的按钮
        $rolesBtn = [];
        foreach ($admin->roles as $k => $v) {
            foreach ($v->modbtn as $key => $vo) {
                if (isset($rolesBtn[$key])) { //如果己有数据进行合并然后去重
                    $rolesBtn[$key] = array_merge($rolesBtn[$key], $vo);
                    $rolesBtn[$key] = array_unique($rolesBtn[$key]);
                } else {
                    $rolesBtn[$key] = $vo;
                }
            }
        }
        //额外按钮
        $cludebtn = $admin->cludebtn;
        foreach ($cludebtn as $m => $v) {
            if (isset($rolesBtn[$m])) {
                $rolesBtn[$m] = array_merge($rolesBtn[$m], $v);
            } else {
                $rolesBtn[$m] = $v;
            }
        }
        //排除按钮
        $excludebtn = $admin->excludebtn;
        foreach ($rolesBtn as $m => $v) {
            foreach ($v as $k => $vo) {

                if (isset($excludebtn[$m]) && in_array($vo, $excludebtn[$m])) {
                    unset($rolesBtn[$m][$k]);
                }
            }
            $rolesBtn[$m] = array_values($rolesBtn[$m]);
        }
        $admin->rolesBtn = $rolesBtn;

        $map[] = ['status', '=', 1];
        $map[] = ['id', 'in', $myrules];

        $dataList = Rule::with('mod')->where($map)->withoutField('name')->order('sort', 'asc')->select()->toArray();
        $dataList=self::rulebtn($dataList);
        $admin->routes = generateTree($dataList);
        $admin->rolesRules=$rolesRules;
        return $admin;
    }
    //按钮加入路由菜单
    public static function rulebtn($data){
        $sysMod=Config::get('app.sysModel.sysmod');
        $sysMod=array_column($sysMod,null,'id');


        $dbaction=db::name('actions')->column('*','name');

        foreach ($data as $v){
            if($v['type']==2&&isset($sysMod[$v['mod_id']])){
                $actions=$sysMod[$v['mod_id']]['actions'];
                foreach($actions as $vo){
                    $item=[];
                    $item['id']=md5($v['id'].$vo);
                    $item['pid']=$v['id'];
                    $item['path']=$v['path'].'/'.$vo;
                    $item['type']=3;
                    $item['title']=$dbaction[$vo]['title'];
                    $data[]=$item;
                }
            }
            if($v['type']==2&&isset($v['mod'])){
                $actions=$v['mod']['actions'];
                foreach($actions as $vo){
                    $item=[];
                    $item['id']=md5($v['id'].$vo);
                    $item['pid']=$v['id'];
                    $item['path']=$v['path'].'/'.$vo;
                    $item['type']=3;
                    $item['title']=$dbaction[$vo]['title'];
                    $data[]=$item;
                }
            }
        }

        return $data;
    }


    public static function test()
    {
        $data = self::withCount(['roles'])->select();
        return $data->toArray();
    }

    //数据写入后事件
    public static function onAfterWrite($data)
    {
        if ($data['roles_id']) {
            //删除角色
            $data->roles()->detach();
            //增加角色
            $data->roles()->saveAll($data['roles_id']);
        }
    }

    //数据删除后事件
    public static function onAfterDelete($data)
    {
        //删除角色
        $data->roles()->detach();
    }
    public function setPasswordAttr($value)
    {
        return $value;
    }
    public static function login($data)
    {

        $where[] = ['username', '=', $data['username']];
        $where[] = ['status', '=', 1];
        if ($admin = self::where($where)->find()) {

            if ($admin->password != md5($data['password'] . $admin->salt)) {
                return 0;
            } else {
                $admin->last_ip = $data['ip'];
                $admin->save();
                return $admin;
            }
        } else {
            return 0;
        }
    }
    public function roles()
    {
        return $this->belongsToMany(Roles::class, 'access');
    }

//个人权限
    public function setCluderulesAttr($value)
    {
        if($value){
            return implode(',', $value);
        }
        
    }
    public function getCluderulesAttr($value)
    {
        if ($value) {
            return explode(',', $value);
        } else {
            return [];
        }
    }
    public function setCludebtnAttr($value)
    {
        if ($value) {
            return json_encode($value);
        }
    }
    public function getCludebtnAttr($value)
    {
        if ($value) {
            return json_decode($value);
        } else {
            return [];
        }
    }
    public function setExcluderulesAttr($value)
    {
        if($value){
            return implode(',', $value);
        }

    }
    public function getExcluderulesAttr($value)
    {
        if ($value) {
            return explode(',', $value);
        } else {
            return [];
        }
    }
    public function setExcludebtnAttr($value)
    {
        if ($value) {
            return json_encode($value);
        }
    }
    public function getExcludebtnAttr($value)
    {
        if ($value) {
            return json_decode($value, true);
        } else {
            return [];
        }
    }
    public function Access()
    {
        return $this->hasMany(Access::class);
    }

}
